#include "netconnecttestform.h"
#include "ui_netconnecttestform.h"
#include "rtc6/RTC6impl.hpp"
#include <QDebug>

NetConnectTestForm::NetConnectTestForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::NetConnectTestForm)
{
    ui->setupUi(this);
}

NetConnectTestForm::~NetConnectTestForm()
{
    delete ui;
}

void NetConnectTestForm::slot_onCheckConnect(int cardNum, bool connect,
                                             int disconnectCount,  int connectCount, uint errCode)
{
    int row = cardNum - 1;
    QTableWidgetItem *item2 = ui->tableWidget->item(row, 2);
    if (!item2) {
        item2 = new QTableWidgetItem(connect ? "已连接" : "已断开");
        ui->tableWidget->setItem(row, 2, item2);
    } else {
        item2->setText(connect ? "已连接" : "已断开");
    }

    QTableWidgetItem *item3 = ui->tableWidget->item(row, 3);
    if (!item3) {
        item3 = new QTableWidgetItem(QString::number(disconnectCount));
        ui->tableWidget->setItem(row, 3, item3);
    } else {
        item3->setText(QString::number(disconnectCount));
    }

    QTableWidgetItem *item4 = ui->tableWidget->item(row, 4);
    if (!item4) {
        item4 = new QTableWidgetItem(QString::number(connectCount));
        ui->tableWidget->setItem(row, 4, item4);
    } else {
        item4->setText(QString::number(connectCount));
    }

    QTableWidgetItem *item5 = ui->tableWidget->item(row, 5);
    if (!item5) {
        item5 = new QTableWidgetItem(QString::number(errCode));
        ui->tableWidget->setItem(row, 5, item5);
    } else {
        item5->setText(QString::number(errCode));
    }
}

QTableWidgetItem* getItemByStr(const QString& name)
{
    QTableWidgetItem* item = new QTableWidgetItem();
    item->setText(name);
    item->setTextAlignment(Qt::AlignCenter);
    return item;
}

void NetConnectTestForm::on_pushButton_search_clicked()
{
    ui->tableWidget->clear();
    if(!utils.isEmpty()){
        for(int i = 0; i < utils.size(); i++){
            NetCardUtil* util = utils.takeAt(i);
            disconnect(util, &NetCardUtil::sig_onCheckConnect,
                       this, &NetConnectTestForm::slot_onCheckConnect);
            delete util;
        }
    }
    // Search for and initialize Ethernet boards
    const auto ethSearchIP = eth_convert_string_to_ip(ui->lineEdit_ip->text().toLocal8Bit().data());
    const auto ethSearchNetmask = eth_convert_string_to_ip(ui->lineEdit_mask->text().toLocal8Bit().data());
    const auto result = eth_search_cards(ethSearchIP, ethSearchNetmask);

    if(result != 0){
        const auto foundEthCards = eth_found_cards();
        qDebug() << "网络RTC6卡数量为：" << foundEthCards;
        ui->tableWidget->setColumnCount(6);
        ui->tableWidget->setRowCount(foundEthCards);
        ui->tableWidget->setHorizontalHeaderLabels({"IP", "序列号", "状态", "断线次数", "连接次数", "当前错误码"});
        for (auto searchCard = 1U; searchCard <= foundEthCards; searchCard++)
        {
            std::array<uint, 16> cardInfo;
            eth_get_card_info_search(searchCard, (uint)cardInfo.data());
            const auto serialNumber = cardInfo[1];
            const auto ipAddress = cardInfo[2];

            int card = eth_assign_card_ip(ipAddress, 0);
            char str[64];
            eth_convert_ip_to_string(ipAddress,(ULONG_PTR)(str));
            QString addrStr = QString(str);
            QString snStr = QString::number(serialNumber);
            if (card <= 0)
            {
                qDebug() << "添加网络卡失败： " << snStr << addrStr << " 代码: " << card;
                continue;
            }

            uint load = n_load_program_file(card, nullptr);
            if(load != 0){
                qDebug() << "n_load_program_file failed： " << load;
                continue;
            }
            uint select = acquire_rtc(card);
            if(select != card){
                qDebug() << "select_rtc failed： " << select;
                continue;
            }
            int row = card - 1;
            ui->tableWidget->setItem(row, 0, getItemByStr(addrStr));
            ui->tableWidget->setItem(row, 1, getItemByStr(snStr));
            ui->tableWidget->setItem(row, 2, getItemByStr("已连接"));
            ui->tableWidget->setItem(row, 3, getItemByStr("0"));
            ui->tableWidget->setItem(row, 4, getItemByStr("0"));
            ui->tableWidget->setItem(row, 5, getItemByStr("0"));

            NetCardUtil* util = new NetCardUtil(card);
            util->start();
            connect(util, &NetCardUtil::sig_onCheckConnect,
                    this, &NetConnectTestForm::slot_onCheckConnect);
            utils.append(util);

        }
        ui->tableWidget->resizeColumnsToContents();
    }
}
